package com.weic.easycache.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.WindowManager;

@TargetApi(Build.VERSION_CODES.FROYO)
public class BrightnessUtils {

	/**判断是否开启了自动亮度调节**/
	public static boolean isAutoBrightness(ContentResolver contentResolver) {
		return checkAutoBrightness(contentResolver) == 1;
	}

	public static int checkAutoBrightness(ContentResolver contentResolver) {
		int autoBrightness = -1;
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			try {
				autoBrightness = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE)
						== Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC ? 1 : 0;
			} catch (SettingNotFoundException e) {
				e.printStackTrace();
			}
		}
		return autoBrightness;
	}

	/**获取屏幕的亮度
	 * @return 0~255**/
	public static int getScreenBrightness(ContentResolver contentResolver) {
		int brightnessValue = 0;
		try {
			brightnessValue = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return brightnessValue;
	}

	/**设置亮度并且关闭自动亮度调节
	 * @param brightness 0~255之间，小于0表示使用系统默认自动亮度**/
	public static void setAndStopAutoBrightness(Activity activity, int brightness) {
		setBrightness(activity, brightness);
		stopAutoBrightness(activity.getContentResolver());
	}

	/**设置亮度
	 * @param brightness 0~255之间，小于0表示使用系统默认自动亮度**/
	public static void setBrightness(Activity activity, int brightness) {
		if(brightness > 1) throw new IllegalArgumentException("参数brightness必须为0~1之间");
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.screenBrightness = brightness * 1.0f / 255.0f;
		activity.getWindow().setAttributes(lp);
	}

	/**停止自动亮度调节**/
	public static void stopAutoBrightness(ContentResolver contentResolver) {
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			Settings.System.putInt(contentResolver,
					Settings.System.SCREEN_BRIGHTNESS_MODE,
					Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
		}
	}

	/**开启亮度自动调节 **/
	public static void startAutoBrightness(Activity activity) {
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			Settings.System.putInt(activity.getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS_MODE,
					Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
		}
	}

	/**保存亮度设置状态
	 * @param brightness 0~255**/
	public static void saveBrightness(ContentResolver resolver, int brightness) {
		Uri uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
		android.provider.Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
		resolver.notifyChange(uri, null);
	}
}
